<?php

if (!defined('IN_XLP')) {
    exit('Access Denied!');
}

/**
 * Description of reply
 * 自定义回复处理
 * @author xlp
 */
class replyApi {

    public $replyList = null;
    public $replyFile; //缓存文件名
    public $info;
    public $text = ''; //输入内容
    protected $eventConfig = null;

    function __construct(&$info) {
        $this->info = $info;
        //缓存文件名
        $this->replyFile = 'ste_replyCache_u' . $this->info['city_id'];
        //缓存自定义回复
        $this->replyList = F($this->replyFile);
        if (!$this->replyList) {
            $this->replyList = M('ste_reply')->field('id,keyword,match_type,reply_type,content,fid')->where(array('city_id' => $this->info['city_id'], 'status' => 1))->findAll();
            if ($this->replyList) {
                F($this->replyFile, $this->replyList);
            }
        }
    }

    //
    function reply($text) {
        $this->text = $text;
        if ($this->replyList) {
            foreach ($this->replyList as $key => $val) {
                if (strExists($val['keyword'], '|')) {//如果是多关键词
                    foreach (explode('|', $val['keyword']) as $value) {
                        if ($value && (strExists($this->text, $value) || strExists($value, $this->text))) {//匹配成功
                            $return = $this->checkReply($key);
                            if ($return) {
                                return $return;
                            }
                        }
                    }
                } elseif (strExists($this->text, $val['keyword']) || strExists($val['keyword'], $this->text)) {
                    $return = $this->checkReply($key);
                    if ($return) {
                        return $return;
                    }
                }
            }
        }
        return null; //此处返回默认无结果回复
    }

    function checkReply($key) {
        //match_type:0全匹配;1:模糊匹配
        if (strExists($this->replyList[$key]['keyword'], '|')) {//如果是多关键词
            foreach (explode('|', $this->replyList[$key]['keyword']) as $value) {
                if ($value && (($this->replyList[$key]['match_type'] == 0 && $value == $this->text) || $this->replyList[$key]['match_type'] == 1 && strExists($this->text, $value))) {//匹配成功
                    return $this->getReply($key);
                }
            }
        } elseif (($this->replyList[$key]['match_type'] == 0 && $this->replyList[$key]['keyword'] == $this->text) || ($this->replyList[$key]['match_type'] == 1 && strExists($this->text, $this->replyList[$key]['keyword']))) {
            return $this->getReply($key);
        }
        return null; //此处返回默认无结果回复
    }

    //匹配成功，根据类型来处理
    function getReply($key) {
        switch ($this->replyList[$key]['reply_type']) {
            case 0://纯文本
                return $this->replyList[$key]['content'];
            case 1://图文
                return $this->replyNews($this->replyList[$key]['fid']);
            case 2://执行动作
                return $this->replyAction($key);
            case 3://互动
                return $this->replyEvent($this->replyList[$key]['fid']);
        }
    }

    //执行动作
    function replyAction($key) {
        $note = '抱歉，动作调用错误-' . $this->replyList[$key]['fid'];
        $isSaveLog = true;
        $message = null;
        $action = null; //回调执行动作
        switch ($this->replyList[$key]['fid']) {
            case 1://获取订单
			    switch($this->info['groupid']){
					case 3:
					  $os=M("ste_order")->where(array("status"=>4,"deployment_uid"=>$this->info['user_id']))->findAll();
						$note = array(
							'type' => 'news',
							'items' => array(
								array(
									'title' => $this->info['real_name'].',你还有'.count($os).'个订单待配货'
								)
						));
						$os1 = array_slice($os,0,8);
						foreach($os1 as $ok=>$ov){
						    $od['title']="订单".$ov['order_id'];
							$od['picurl']="http://ww4.sinaimg.cn/bmiddle/7d1b3e4fgw1emidyif1xsj200100104g.jpg";
							$od['url']="http://wx.51jhome.com/steward/worker/orderdetail/oid/".$ov['order_id'].".html";
						    $note['items'][]=$od;
						}
						if(count($os)>8){
							$odt['title']="点击查看所有订单";
							$odt['url']="http://wx.51jhome.com/steward/worker/orderlist.html";
							$note['items'][]=$odt;
						}
					  break;  
					case 4:
					    $os=M("ste_order")->where(array("status"=>6,"worker_uid"=>$this->info['user_id']))->findAll();
						$note = array(
							'type' => 'news',
							'items' => array(
								array(
									'title' => $this->info['real_name'].',你还有'.count($os).'个订单待配货'
								)
						));
						$os1 = array_slice($os,0,8);
						foreach($os1 as $ok=>$ov){
						    $od['title']="订单".$ov['order_id'];
							$od['picurl']="http://ww4.sinaimg.cn/bmiddle/7d1b3e4fgw1emidyif1xsj200100104g.jpg";
							$od['url']="http://wx.51jhome.com/steward/worker/orderdetail/oid/".$ov['order_id'].".html";
						    $note['items'][]=$od;
						}
						if(count($os)>8){
							$odt['title']="点击查看所有订单";
							$odt['url']="http://wx.51jhome.com/steward/worker/orderlist.html";
							$note['items'][]=$odt;
						}
					  break;
					default:
					  $note = '对不起，只有小管家和配货员才能查看任务';
				}
                break;
        }
        return array('note' => $note, 'isSaveLog' => $isSaveLog, 'message' => $message, 'action' => $action);
    }

    //回复互动
    function replyEvent($id) {
        T('weixin/event');
        $event = new eventApi($this->info);
        return $event->replyEvent($id);
    }

    //回复图文
    function replyNews($id) {
        $createTime = TIME;
        $rs = M('article')->field('id,type,title,content,description,picurl,url,infotime')->where(array('fid' => 0, 'id' => $id))->order('id desc')->find();
        $items = array();
        $result = array();
        if ($rs) {
            $result[] = $rs;
            if ($rs['type'] == 2) {//多条图文时
                $rsItem = M('article')->field('id,title,content,description,picurl,url,infotime')->where(array('fid' => $rs['id']))->order('id asc')->limit(0, 8)->findAll();
                if ($rsItem) {
                    $result = array_merge_recursive($result, $rsItem);
                }
            }
            $createTime = $rs['infotime'];
        } else {
            return '内容不存在或已删除';
        }
        if ($result) {
            foreach ($result as $val) {
                $items[] = array(
                    'title' => $val['title'],
                    'createTime' => $val['infotime'],
                    'description' => $val['description'],
                    'picurl' => getImgUrl($val['picurl']),
                    'url' => !$val['content'] && $val['url'] ? $val['url'] : U('news/detail', array('id' => $val['id']))
                );
            }
        }
        return array('type' => 'news', 'items' => $items, 'createTime' => $createTime);
    }

}
